// DriveNotes. Copyright (c) 2011, Andrei Senchuk. All rights reserved.
package net.taviscaron.drivenotes.web.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.taviscaron.drivenotes.shared.model.entity.Car;
import net.taviscaron.drivenotes.shared.model.entity.Charging;
import net.taviscaron.drivenotes.shared.model.entity.User;
import net.taviscaron.drivenotes.shared.service.ChargingService;
import net.taviscaron.drivenotes.shared.service.GarageService;
import net.taviscaron.drivenotes.web.core.Constants;
import net.taviscaron.drivenotes.web.forward.RequestForwarder;
import net.taviscaron.drivenotes.web.forward.ViewForward;
import org.springframework.beans.factory.annotation.Required;

/**
 * Charging action
 * @author Andrei Senchuk
 */
public class ChargingAction implements Action {
    private ChargingService chargingService;
    private GarageService garageService;

    @Required
    public void setGarageService(GarageService garageService) {
        this.garageService = garageService;
    }

    @Required
    public void setChargingService(ChargingService chargingService) {
        this.chargingService = chargingService;
    }

    public RequestForwarder doAction(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = (User)request.getAttribute(Constants.AUTHORIZED_USER_ATTR_NAME);
        List<Car> cars = garageService.findCarsByOwnerId(user.getId());
        Map<Car, List<Charging>> carChargings = new HashMap<Car, List<Charging>>();
        for(Car car : cars) {
            List<Charging> chargings = chargingService.findChargingsByCar(car);
            carChargings.put(car, chargings);
        }
        request.setAttribute("cars", cars);
        request.setAttribute("carChargings", carChargings);
        return new ViewForward("charging");
    }
}
